<script setup>
import reserveApi from '@/api/reserveApi';
import { reactive, ref, watch } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus'
import courseApi from '@/api/courseApi';
import memberApi from '@/api/memberApi';

const course = defineModel();
// 可以直接侦听一个 ref
watch(course, async (newCourse, oldCourse) => {
        console.log('监听值的变化');
        addReserve.value.courseId = newCourse.id;
        loadReserves();
    }
);

const reserves = ref([]);

// 分页信息
const pageInfo = reactive({
    page: 1,
    limit: 10,
    total: 0,
})

// 获取预约列表
loadReserves();

// 页码和页面大小更新
function loadReserves() {
    pageInfo.courseId = course.value.id;
    console.log('loadReserves===请求参数：', pageInfo); // 检查courseId是否存在
    reserveApi.search(pageInfo).then(result => {
        reserves.value = result.data.list;
        pageInfo.total = result.data.total;
    });
}

// 添加的相关操作
const addVisible = ref(false);
const addReserve = ref({courseId: course.id});
function showAdd() {
    addVisible.value = true;    // 显示添加窗口
}

function handleAdd(){
    reserveApi.add(addReserve.value).then(result=>{
        if (result.code == 200) {
            ElMessage({ message: '预约创建成功！', type: 'success' })
            addVisible.value = false;
            addReserve.value = {courseId: course.id};
        } else {
            ElMessage.error(result.msg);
        }
        // 刷新表格数据
        loadReserves();
    });
}

// 编辑的操作
const editVisible = ref(false);
const editReserve = ref({});

function showEdit(row){
    editVisible.value = true;
    editReserve.value = JSON.parse(JSON.stringify(row));   // 深拷贝
    editReserve.value.password = "";
    console.log(row);
}

function handleEdit(){
    reserveApi.edit(editReserve.value).then(result=>{
        if (result.code == 200) {
            ElMessage({ message: '编辑预约成功！', type: 'success' })
            editVisible.value = false;
        } else {
            ElMessage.error(result.msg);
        }
        // 刷新表格数据
        loadReserves();
    });
}
function handleCancel(row, status){
    ElMessageBox.confirm(
        [   '亲，确定要取消当前预约么?',//0
            '亲，确定要重新预约么?',//1
            '亲，确定要签到么?',//2
            '亲，确定要未到么?',][status],//3
        '警告',
        {
            confirmButtonText: '确定',
            cancelButtonText: '不了',
            type: 'warning',
        }
    ).then(()=>{
        // 确定
        editReserve.value = JSON.parse(JSON.stringify(row));   // 深拷贝
        editReserve.value.password = "";
        editReserve.value.status = status;
        // reserveApi.edit(editReserve.value).then(result=>{
        //     if (result.code == 200) {
        //         ElMessage({ message: [  '取消预约成功！',
        //                                 '重新预约成功！',
        //                                 '签到成功！',
        //                                 '未到成功！',][status], type: 'success' })
        //     } else {
        //         ElMessage.error(result.msg);
        //     }
        //     // 刷新表格数据
        //     loadReserves();
        // });
        reserveApi.editStatus(editReserve.value).then(result=>{
            if (result.code == 200) {
                ElMessage({ message: [  '取消预约成功！',
                                        '重新预约成功！',
                                        '签到成功！',
                                        '未到成功！',][status], type: 'success' })
            } else {
                ElMessage.error(result.msg);
            }
            // 刷新表格数据
            loadReserves();
        });
    });
}

// 解析类型显示
function fmtStatus(row, column, cellValue, index) {
    return ['已取消','已预订', '已签到', '未签到'][row.status];
}

// 下拉列表
const members = ref([]);
const courses = ref([]);

loadCourses();
loadMembers();

// 页码和页面大小更新
function loadCourses() {
    courseApi.search().then(result => {
        courses.value = result.data;
    });
}
function loadMembers() {
    memberApi.search().then(result => {
        members.value = result.data;
    });
}

function onSearch(){
    pageInfo.page = 1;
    loadReserves();
}

// 多选
const selectedReserves = ref([])
function handleSelectionChange(val){
    selectedReserves.value = JSON.parse(JSON.stringify(val));    // 深拷贝
}
// 批量处理
function handleBatchSign(status){
    ElMessageBox.confirm(
        [   '亲，确定要批量取消预约么?',
            '亲，确定要批量重新预约么?',
            '亲，确定要批量签到么?',
            '亲，确定要批量未到么?',][status],
        '警告',
        {
            confirmButtonText: '确定',
            cancelButtonText: '不了',
            type: 'warning',
        }
    ).then(()=>{
        // 确定
        for (let reserve of selectedReserves.value){
            reserve.status = status;
        }
        reserveApi.batchSign(selectedReserves.value).then(result=>{
            if (result.code == 200) {
                ElMessage({ message: [  '批量取消预约成功！',
                                        '批量重新预约成功！',
                                        '批量签到成功！',
                                        '批量未到成功！',][status], type: 'success' })
            } else {
                ElMessage.error(result.msg);
            }
            // 刷新表格数据
            loadReserves();
        });
    });
}

</script>

<template>
    <div class="content">
        <el-row justify="space-between">
            <!-- 按钮 -->
            <el-col :span="12">
                <el-button type="primary" @click="showAdd" >添加预约</el-button>
                <el-button type="success" @click="handleBatchSign(2)" >批量签到</el-button>
                <el-button type="danger" @click="handleBatchSign(3)" >批量未到</el-button>
                <el-button type="primary" @click="handleBatchSign(1)" >重新预约</el-button>
                <el-button type="warning" @click="handleBatchSign(0)" >取消预约</el-button>
            </el-col>
            <!-- 搜索栏 -->
            <el-col :span="12">
                <el-form :model="pageInfo" :inline="true" >          
                    <el-form-item label="会员" :label-width="60">
                        <el-select
                            v-model="pageInfo.memberId"
                            filterable
                            placeholder="请选择会员"
                            style="width: 240px"
                            clearable
                        >
                            <el-option
                            v-for="item in members"
                            :key="item.id"
                            :label="item.name + '-' + item.phone"
                            :value="item.id"
                            />
                        </el-select>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="onSearch"><el-icon><Search></Search></el-icon></el-button>
                    </el-form-item>
                </el-form>
            </el-col>
        </el-row>
        <!-- 预约学员列表 -->
        <el-table :data="reserves" :stripe="true" :border="true" style="width: 100%"
            @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="40" >
            </el-table-column>
            <el-table-column prop="id" label="ID" width="60" />
            <el-table-column prop="member.name" label="会员"  width="100"/>
            <el-table-column prop="reserveTime" label="预约时间" width="180" />
            <el-table-column prop="score" label="评分"  width="60"/>
            <el-table-column prop="comment" label="评语" />
            <el-table-column prop="commentTime" label="评价时间" width="180" />
            <el-table-column prop="status" label="状态" width="80" :formatter="fmtStatus"/>
            <el-table-column label="操作" width="220">
                <template #default="scope">
                    <el-button size="small" type="success" v-if="scope.row.status==1 || scope.row.status==3"
                        @click="handleCancel(scope.row, 2)">签到</el-button> 
                    <el-button size="small" type="danger" v-if="scope.row.status==1 || scope.row.status==2"
                        @click="handleCancel(scope.row, 3)">未到</el-button> 
                    <el-button size="small" type="primary" v-if="scope.row.status==0"
                        @click="handleCancel(scope.row, 1)">重新预订</el-button> 
                    <el-button size="small" type="warning" v-if="scope.row.status==1"
                        @click="handleCancel(scope.row, 0)">取消预订</el-button> 
                </template>
            </el-table-column>
        </el-table>
        <el-pagination class="page" v-model:current-page="pageInfo.page" v-model:page-size="pageInfo.limit"
            :total="pageInfo.total" :page-sizes="[10, 20, 50, 100]" :background="true"
            layout="total, sizes, prev, pager, next, jumper" @change="loadReserves" />
    </div>

    <!-- 添加的弹窗 -->
    <el-dialog v-model="addVisible" title="创建新预约" width="500">
        <el-form :model="addReserve">
            <el-form-item label="会员" :label-width="60">
                <el-select
                    v-model="addReserve.memberId"
                    filterable
                    placeholder="请选择会员"
                    style="width: 240px"
                >
                    <el-option
                    v-for="item in members"
                    :key="item.id"
                    :label="item.name + '-' + item.phone"
                    :value="item.id"
                    />
                </el-select>
            </el-form-item>
            <el-form-item label="课程" :label-width="60">
                <el-select
                    v-model="addReserve.courseId"
                    filterable
                    placeholder="请选择课程"
                    style="width: 240px"
                >
                    <el-option
                    v-for="item in courses"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                    />
                </el-select>
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="addVisible = false">取消</el-button>
                <el-button type="primary" @click="handleAdd">
                    立即预约
                </el-button>
            </div>
        </template>
    </el-dialog>

    <!-- 编辑的弹窗 -->
    <el-dialog v-model="editVisible" title="编辑预约" width="500">
        <el-form :model="editReserve">
            <el-form-item label="会员" :label-width="60">
                <el-select
                    v-model="editReserve.memberId"
                    filterable
                    placeholder="请选择会员"
                    style="width: 240px"
                >
                    <el-option
                    v-for="item in members"
                    :key="item.id"
                    :label="item.name + '-' + item.phone"
                    :value="item.id"
                    />
                </el-select>
            </el-form-item>
            <el-form-item label="课程" :label-width="60">
                <el-select
                    v-model="editReserve.courseId"
                    filterable
                    placeholder="请选择课程"
                    style="width: 240px"
                >
                    <el-option
                    v-for="item in courses"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                    />
                </el-select>
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="editVisible = false">取消</el-button>
                <el-button type="primary" @click="handleEdit">
                    修改预约
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>

<style>

</style>